//
//  YWPhotoView.m
//  maintain
//
//  Created by kyo on 16/11/16.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWPhotoView.h"
#import "UIView+Extension.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "UIImageView+WebCache.h"
#import "UIImage+ProportionalFill.h"
#import "MBProgressHUD.h"
#import "DJWActionSheet.h"
//#import "YWAlertView.h"
#import "MWPhotoBrowser.h"

#import "YWPicture.h"
#import "YWPatrolPicture.h"
#import "YWResourceManager.h"

static NSInteger const maxPhotoCount = 6;
static NSInteger const kViewBaseTag = 300;

@interface YWPhotoView () <UIImagePickerControllerDelegate, UINavigationControllerDelegate,MWPhotoBrowserDelegate> {
    //NSMutableArray *_selections;
    NSInteger photoSize;
    MWPhotoBrowser *browser;
}
@property (nonatomic, strong) NSMutableArray *photos;
@property (nonatomic, strong) NSMutableArray *thumbs;
@property (nonatomic, strong) UIImagePickerController* imagePicker;
@property (nonatomic, strong) NSArray<UIView *> *picViews;
@property (nonatomic, weak) MBProgressHUD* HUD;

@property (nonatomic, strong) NSMutableArray *totalPhotoArray;
@end

@implementation YWPhotoView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.clipsToBounds = YES;
        photoSize = YWPhotoSize;
        _canAddPhoto = YES;
        _pickFromPhotoLibrary = NO;
        NSMutableArray *picViews = [NSMutableArray new];
        for (int i = 0; i < maxPhotoCount; i++) {
            UIImageView *imageView = [UIImageView new];
            imageView.hidden = YES;
            imageView.exclusiveTouch = YES;
            imageView.tag = kViewBaseTag + i;
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.layer.masksToBounds = YES;
            imageView.userInteractionEnabled = YES;
            [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageViewTapEvent:)]];
            [self addSubview:imageView];
            [picViews addObject:imageView];
        }
        _picViews = picViews;
    }
    return self;
}
- (void)setPhotoWH:(NSInteger)photoWH{
    _photoWH = photoWH;
    photoSize = photoWH;
}

- (void)setPhotosArray:(NSArray *)photosArray{
    _photosArray = photosArray;
    [self.totalPhotoArray removeAllObjects];
    [self.totalPhotoArray addObjectsFromArray:photosArray];
    
    int picsCount = (int)_totalPhotoArray.count;
    NSInteger gap = _noPhotoGap ? 0 : YWPhotoGap;
    CGFloat selfSizeHeight = photoSize*(picsCount/4+1) + gap*(picsCount/4);
    self.bounds = CGRectMake(0, 0, SCREEN_WIDTH, selfSizeHeight);
}

- (void)layoutSubviews{
    [super layoutSubviews];
    [self setupMWPhotos];
    
    int picsCount = (int)_totalPhotoArray.count;
    YWPicture* picture = nil;
    YWPatrolPicture *patrolPicture = nil;
    NSString *pictureName = nil;
    NSString *smallPicUrl = nil;
    BOOL isLoaclPic = NO;
    BOOL hasAdd = NO;
    NSInteger gap = _noPhotoGap ? 0 : YWPhotoGap;
    
    for (int i = 0; i < maxPhotoCount; i++) {
        UIImageView *imageView = (UIImageView*)_picViews[i];
        imageView.frame = CGRectMake(gap + photoSize * (i % 4) + gap * (i % 4 + 1), (i/4)*(photoSize+gap), photoSize, photoSize);
        if (i >= picsCount) {
            //[imageView sd_cancelCurrentImageLoad];
            if (_canAddPhoto && !hasAdd) {
                hasAdd = YES;
                imageView.hidden = NO;
                imageView.image = [UIImage imageNamed:@"scan_addBtn"];
            }else {
                imageView.hidden = YES;
                imageView.image = nil;
            }
        } else {
            imageView.hidden = NO;
            id pic = _totalPhotoArray[i];
            if ([pic isKindOfClass:[NSString class]]) {
                pictureName = (NSString*)pic;
                isLoaclPic = YES;
            }else if ([pic isKindOfClass:[YWPicture class]]) {
                picture = (YWPicture*)pic;
                isLoaclPic = picture.isLocalImage;
                pictureName = picture.pictureName;
                smallPicUrl = picture.smallPictureUrl;
            }else if ([pic isKindOfClass:[YWPatrolPicture class]]){
                patrolPicture = (YWPatrolPicture*)pic;
                isLoaclPic = patrolPicture.isLocalImage;
                pictureName = patrolPicture.pictureName;
                smallPicUrl = patrolPicture.smallUrl;
            }
            
            if (isLoaclPic) {
                NSData* imageData = [[YWResourceManager shareManager] dataFromCacheStorageWithResourcePath:pictureName];
                UIImage* image = [UIImage imageWithData:imageData];
                if (image) {imageView.image = image;}
                else {
                    NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, smallPicUrl];
                    [imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"image_placeholder"]];
                }
            }else {
                NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, smallPicUrl];
                [imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"image_placeholder"]];
            }
        }
    }
}

- (void)setupMWPhotos{
    // Browser
    [self.photos removeAllObjects];
    [self.thumbs removeAllObjects];;
    MWPhoto *photo;
    
    YWPicture* picture = nil;
    YWPatrolPicture *patrolPicture = nil;
    NSString *pictureName = nil;
    NSString *bigPicUrl = nil;
    NSString *smallPicUrl = nil;
    BOOL isLoaclPic = NO;
    
    int count = (int)_totalPhotoArray.count;
    for (int i=0; i<count; i++) {
        id pic = _totalPhotoArray[i];
        if ([pic isKindOfClass:[NSString class]]) {
            pictureName = (NSString*)pic;
            isLoaclPic = YES;
        }else if ([pic isKindOfClass:[YWPicture class]]) {
            picture = (YWPicture*)pic;
            isLoaclPic = picture.isLocalImage;
            pictureName = picture.pictureName;
            bigPicUrl = picture.bigPictureUrl;
            smallPicUrl = picture.smallPictureUrl;
        }else if ([pic isKindOfClass:[YWPatrolPicture class]]){
            patrolPicture = (YWPatrolPicture*)pic;
            isLoaclPic = patrolPicture.isLocalImage;
            pictureName = patrolPicture.pictureName;
            bigPicUrl = patrolPicture.bigUrl;
            smallPicUrl = patrolPicture.smallUrl;
        }
        
        if (isLoaclPic) {
            NSData* imageData = [[YWResourceManager shareManager] dataFromCacheStorageWithResourcePath:pictureName];
            UIImage* image = [UIImage imageWithData:imageData];
            if (image) {
                photo = [MWPhoto photoWithImage:image];
                [_photos addObject:photo];
                [_thumbs addObject:photo];
            }else {
                NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, bigPicUrl];
                [_photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlStr]]];
                urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, smallPicUrl];
                [_thumbs addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlStr]]];
            }
        }else {
            NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, bigPicUrl];
            [_photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlStr]]];
            urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, smallPicUrl];
            [_thumbs addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlStr]]];
        }
    }
}

- (void)handleImageViewTapEvent:(UIGestureRecognizer*)gesture{
    NSInteger tag = gesture.view.tag - kViewBaseTag;
    if (tag == _totalPhotoArray.count) {
        [self showImagePicker];
    }else{
        // Create browser
        browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        browser.displayActionButton = YES;
        browser.displayNavArrows = NO;
        browser.displaySelectionButtons = NO;
        browser.alwaysShowControls = NO;
        browser.zoomPhotosToFill = YES;
        browser.enableGrid = YES;
        browser.startOnGrid = NO;
        browser.enableSwipeToDismiss = NO;
        browser.autoPlayOnAppear = NO;
        [browser setCurrentPhotoIndex:tag];
        if (_canAddPhoto) {
            browser.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(deletePhoto:)];
        }
//        if (browser.displaySelectionButtons) {
//            _selections = [NSMutableArray new];
//            for (int i = 0; i < photos.count; i++) {
//                [_selections addObject:[NSNumber numberWithBool:NO]];
//            }
//        }
        
        [self.viewController.navigationController pushViewController:browser animated:YES];
    }
}

- (void)deletePhoto:(id)sender{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"要删除这张照片吗" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSInteger index = browser.currentIndex;
        [_photos removeObjectAtIndex:index];
        [_thumbs removeObjectAtIndex:index];
        [_totalPhotoArray removeObjectAtIndex:index];
        [self layoutSubviews];
        int picsCount = (int)_totalPhotoArray.count;
        if ([_delegate respondsToSelector:@selector(resetPhotoViewFrame:andTotalPhotoArray:)]) {
            NSInteger gap = _noPhotoGap ? 0 : YWPhotoGap;
            CGFloat selfSizeHeight = photoSize*(picsCount/4+1) + gap*(picsCount/4);
            [_delegate resetPhotoViewFrame:CGRectMake(0, 0, SCREEN_WIDTH, selfSizeHeight) andTotalPhotoArray:self.totalPhotoArray];
        }
        if (_photos.count == 0) {
            [browser.navigationController popViewControllerAnimated:YES];
        }else{
            [browser reloadData];
        }
    }]];
    [browser presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photos.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    if (index < _thumbs.count)
        return [_thumbs objectAtIndex:index];
    return nil;
}

//- (MWCaptionView *)photoBrowser:(MWPhotoBrowser *)photoBrowser captionViewForPhotoAtIndex:(NSUInteger)index {
//    MWPhoto *photo = [self.photos objectAtIndex:index];
//    MWCaptionView *captionView = [[MWCaptionView alloc] initWithPhoto:photo];
//    return [captionView autorelease];
//}

//- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index {
//    YWLog(@"ACTION!");
//}

//- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index {
//    YWLog(@"Did start viewing photo at index %lu", (unsigned long)index);
//}
//
//- (BOOL)photoBrowser:(MWPhotoBrowser *)photoBrowser isPhotoSelectedAtIndex:(NSUInteger)index {
//    return NO;//[[_selections objectAtIndex:index] boolValue];
//}

//- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser titleForPhotoAtIndex:(NSUInteger)index {
//    return [NSString stringWithFormat:@"Photo %lu", (unsigned long)index+1];
//}

//- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index selectedChanged:(BOOL)selected {
//    //[_selections replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:selected]];
//    YWLog(@"Photo at index %lu selected %@", (unsigned long)index, selected ? @"YES" : @"NO");
//}

//- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser {
//    // If we subscribe to this method we must dismiss the view controller ourselves
//    YWLog(@"Did finish modal presentation");
//    [self.viewController dismissViewControllerAnimated:YES completion:nil];
//}

- (void)showImagePicker{
    if (!_pickFromPhotoLibrary) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [self.viewController presentViewController:self.imagePicker animated:YES completion:NULL];
        }else {[self showCameraIsNotAvailableAlertView];}
    }else{
        [self.viewController.view endEditing:YES];
        [self.viewController.navigationController.view endEditing:YES];
        [DJWActionSheet showInView:self.viewController.navigationController.view withTitle:@"请选择"
                 cancelButtonTitle:@"取消"
            destructiveButtonTitle:nil
                 otherButtonTitles:@[ @"拍照", @"从手机相册选择" ]
                          tapBlock:^(DJWActionSheet* actionSheet, NSInteger tappedButtonIndex) {
                              if (tappedButtonIndex != actionSheet.cancelButtonIndex) {
                                  if (tappedButtonIndex == 0) {
                                      self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                                      if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                                          [self.viewController presentViewController:self.imagePicker animated:YES completion:NULL];
                                      }else {
                                          [self showCameraIsNotAvailableAlertView];}
                                  }else if (tappedButtonIndex == 1) {
                                      self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                                      if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                                          [self.viewController presentViewController:self.imagePicker animated:YES completion:NULL];
                                      }else {
                                          [self showPhotoLibraryIsNotAvailableAlertView];}
                                  }
                              }
                          }];
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    self.HUD.labelText = NSLocalizedString(kTextBeingProcessed, nil);
    [self.HUD show:YES];
    [self.viewController dismissViewControllerAnimated:YES  completion:^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            UIImage* photoImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            if (!photoImage) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.HUD hide:YES];
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextErrorOfGetImage, nil)];
                });
                return;
            }
            NSString* bigImageName = [NSString stringWithFormat:@"%@.jpg", [YWCommonTool randStringId]];
            NSString* smallImageName = [[YWResourceManager shareManager] smallPictureName:bigImageName];
            @autoreleasepool{
                CGFloat width = photoImage.size.width;
                CGFloat heigth = photoImage.size.height;
                CGFloat bigSize = 960.0f;
                CGFloat smallSize = 200.0f;
                UIImage* bigImage = photoImage;
                UIImage* smallImage = photoImage;
                if (width > heigth) {
                    if (width > bigSize) {
                        bigImage = [photoImage scaleToSize:CGSizeMake(bigSize * width / heigth, bigSize)];
                    }
                    if (width > smallSize) {
                        smallImage = [photoImage scaleToSize:CGSizeMake(smallSize * width / heigth, smallSize)];
                    }
                }
                else {
                    if (heigth > bigSize) {
                        bigImage = [photoImage scaleToSize:CGSizeMake(bigSize, bigSize * heigth / width)];
                    }
                    if (heigth > smallSize) {
                        smallImage = [photoImage scaleToSize:CGSizeMake(smallSize, smallSize * heigth / width)];
                    }
                }
                NSData* bigImageData = UIImageJPEGRepresentation(bigImage, 0.1);
                NSData* smallImageData = UIImageJPEGRepresentation(smallImage, 0.3);
                [[YWResourceManager shareManager] saveDataToCacheStorage:bigImageData withResourcePath:bigImageName];
                [[YWResourceManager shareManager] saveDataToCacheStorage:smallImageData withResourcePath:smallImageName];
            }
            [self.totalPhotoArray addObject:bigImageName];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.HUD hide:YES];
                //[self addImages:@[ bigImageName ]];
                [self layoutSubviews];
                int picsCount = (int)_totalPhotoArray.count;
                if ([_delegate respondsToSelector:@selector(resetPhotoViewFrame:andTotalPhotoArray:)]) {
                    NSInteger gap = _noPhotoGap ? 0 : YWPhotoGap;
                    CGFloat selfSizeHeight = photoSize*(picsCount/4+1) + gap*(picsCount/4);
                    [_delegate resetPhotoViewFrame:CGRectMake(0, 0, SCREEN_WIDTH, selfSizeHeight) andTotalPhotoArray:self.totalPhotoArray];
                }
            });
        });
    }];
}

- (void)showCameraIsNotAvailableAlertView
{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(kTextCameraIsNotAvailable, nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleCancel handler:nil]];
    [self.viewController presentViewController:alertController animated:YES completion:nil];
}

- (void)showPhotoLibraryIsNotAvailableAlertView
{
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:@"您的图片库不可用" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleCancel handler:nil]];
    [self.viewController presentViewController:alertController animated:YES completion:nil];
}

- (NSMutableArray *)totalPhotoArray{
    if (!_totalPhotoArray) {
        _totalPhotoArray = [NSMutableArray array];
    }
    return _totalPhotoArray;
}

- (NSMutableArray *)photos{
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}

- (NSMutableArray *)thumbs{
    if (!_thumbs) {
        _thumbs = [NSMutableArray array];
    }
    return _thumbs;
}

- (UIViewController*)viewController
{
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

- (UIImagePickerController*)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    return _imagePicker;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextSubmitTask, nil);
        hud.dimBackground = YES;
        // hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.viewController.navigationController.view addSubview:hud];
    }
    return _HUD;
}

@end
